package com.sofwin.configer;

import com.sofwin.common.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @packageName: com.sofwin.configer
 * @user: andyliu
 * @date: 2021/12/21 11:37
 * @email 115176513@qq.com
 * @description: TODO
 */
@Configuration
@Component
public class ShrioConfiger {
    @Autowired
    private MyRealm myRealm;

    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        // 创建shiroFilter工厂bean
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        // 设置授权和放行规则
        Map<String,String> definitions = new HashMap<>();
        definitions.put("/**","authc");
        // 静态资源不需要认证
        definitions.put("/static/**","anon");
        definitions.put("/verification","anon");
        definitions.put("/index.html","anon");
        bean.setFilterChainDefinitionMap(definitions);
        bean.setLoginUrl("/index.html");
        bean.setSecurityManager(getSecurityManager());
        return bean;
    }

    /**
     * DefaultSecurityManager用于javase的安全验证
     *
     * @return
     */
    @Bean
    public DefaultWebSecurityManager getSecurityManager(){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        myRealm.setCredentialsMatcher(this.hashedCredentialsMatcher());
        manager.setRealm(myRealm);
        return manager;
    }
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        // 散列算法的密码校验器
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");// 设置加密算法的方式
        matcher.setHashIterations(1);// hash的次数
        matcher.setStoredCredentialsHexEncoded(true);// 是否使用散列方式进行密码编码
        return matcher;
    }
}
